unit ec_inputnumber;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ButtonPanel, StdCtrls,
  EditBtn, Spin, ec_base;

type

  { TECInputNumberFrame }

  TECInputNumberFrame = class(TECBaseFrame)
    NumDigitsLabel: TLabel;
    NumDigitsSpinEdit: TSpinEdit;
    VariableEditButton: TEditButton;
    VariableLabel: TLabel;
    procedure VariableEditButtonButtonClick(Sender: TObject);
    procedure VariableEditButtonKeyPress(Sender: TObject; var Key: char);
  private
    VariableId: Integer;
    procedure UpdateVariableName;
  public
    procedure InitNew; override;
    procedure InitExisting; override;
    procedure MakeResultingCommand; override;
  end;

var
  ECInputNumberFrame: TECInputNumberFrame;

implementation

uses
  namedindexselection, fpjson, constants;

{$R *.lfm}

{ TECInputNumberFrame }

procedure TECInputNumberFrame.VariableEditButtonButtonClick(Sender: TObject);
begin
  VariableId := NamedIndexSelectionForm.SelectVariable(VariableId, Db);
  UpdateVariableName
end;

procedure TECInputNumberFrame.VariableEditButtonKeyPress(Sender: TObject;
  var Key: char);
begin
  Key := #0;
  VariableEditButtonButtonClick(Sender);
end;

procedure TECInputNumberFrame.UpdateVariableName;
begin
  VariableEditButton.Text := Db.GetVariableName(VariableId);
end;

procedure TECInputNumberFrame.InitNew;
begin
  VariableId := 1;
  UpdateVariableName
end;

procedure TECInputNumberFrame.InitExisting;
var
  Params: TJSONArray = nil;
  NumDigits: Integer;
begin
  Params := GetFirstParams;

  VariableId := 1;
  if (Params <> nil) and (Params.Count >= 1) and (Params[0].JSONType = jtNumber) then
     VariableId := Params.Integers[0];
  UpdateVariableName;

  NumDigits := 1;
  if (Params <> nil) and (Params.Count >= 2) and (Params[1].JSONType = jtNumber) then
     NumDigits := Params.Integers[1];
  NumDigitsSpinEdit.Value := NumDigits;
end;

procedure TECInputNumberFrame.MakeResultingCommand;
begin
  ResultingCommand := TJSONArray.Create([
    TJSONObject.Create([
      'code', INPUT_NUMBER_EC_CODE,
      'indent', Indent,
      'parameters', TJSONArray.Create([VariableId, NumDigitsSpinEdit.Value])
    ])
  ]);
end;

end.

